package com.coder520.sync_learning.demo;

import org.omg.CORBA.Current;

import java.io.Console;
import java.util.Currency;
import java.util.LinkedList;

public class EventQueue {
    private final int max;


    static  class Evnet{

    }

    private final LinkedList<Evnet> eventQueue=new LinkedList<>();

    private final static  int DEFAULT_MAX_EVENT=10;

    EventQueue(int max){
        this.max = max;
    }

    EventQueue(){
        this(DEFAULT_MAX_EVENT);
    }


    public void offer(Evnet evnet){
        synchronized (eventQueue){
            if (eventQueue.size()>=max){
                try {
                    console(" the queue is full;");
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            console(" the new event is submited");
            eventQueue.addLast(evnet);
            eventQueue.notify();
        }
    }


    public Evnet task(){
        synchronized (eventQueue){
            if (eventQueue.isEmpty()){
                try {
                    console("the queue is empty.");
                    eventQueue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            Evnet evnet=eventQueue.removeFirst();
            this.eventQueue.notify();
            console("the event "+ evnet+" is handled");
            return evnet;
        }

    }
    private void console(String s) {
        System.out.printf("%s:%s\n", Thread.currentThread().getName(),s);
    }
}
